package quant.smart.crawl.domain;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.google.common.collect.ImmutableList;

import quant.smart.crawl.cmd.BaseCommand;
import quant.smart.crawl.cmd.ClientContext;
import quant.smart.crawl.cmd.ClientFactory;
import quant.smart.crawl.cmd.CommandFactory;
import quant.smart.crawl.dao.LmeInventoryDao;
import quant.smart.crawl.model.Inventory;
import quant.smart.crawl.model.SmartResponse;
import quant.smart.crawl.utils.Constants;
import quant.smart.crawl.utils.TimeUtil;

@Service
public class LmeService extends ServiceBase {
	final Log logger=LogFactory.getLog(getClass());
	
	@Autowired
	LmeInventoryDao inventoryDao;
	
	@Autowired
	ClientFactory clientFactory;
	
	//线程池数组，每个方法一个线程池
	ImmutableList<ExecutorService> executors = ImmutableList.of(Executors.newFixedThreadPool(10),
			Executors.newFixedThreadPool(10));
	
	public void collect(){
		//按时间戳查询，如果已经存在则不下载
		String timesSn =TimeUtil.toString(new Date(), TimeUtil.YYYYMMDD);
		List<Inventory> findRes= inventoryDao.findByProperty(new Inventory(timesSn));
		if(!findRes.isEmpty()) return;

		CompletionService<Object> ecs = new ExecutorCompletionService<Object>(executors.get(0));
		//多个目标网站查询
		int cmdCount =0;
		Map<String,ClientContext> pool =clientFactory.getClientPool();
		for (Map.Entry<String, ClientContext> entry : pool.entrySet()) {			
			ClientContext client = entry.getValue();
			BaseCommand modelCmd = CommandFactory.create(client,Constants.OPT_LME_COLLECT);			
			ecs.submit(modelCmd);
			cmdCount++;
		}
		SmartResponse res =null;
		try {
			//最先返回的返回，后面的丢弃
			for (int i = 0; i < cmdCount; i++) {
				Future<Object> resFuture = ecs.take();
				res = (SmartResponse) getAndWaitResult(resFuture);
				if (StringUtils.endsWithIgnoreCase(res.getCode(), Constants.RETURN_SUCCESS)){
					break;
				}
			}
			if(res!=null){
				List<Inventory> list=(List<Inventory>) res.getData();
				for(Inventory rec :list){
					inventoryDao.insert(rec);
				}
			}
		} catch (Exception e) {
			logger.error("处理错误",e);
		}
	}
	
	public Inventory findById(String id){
		return inventoryDao.findById(id);
	}
}
